package com.ruoyi.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate() {
        // 创建请求工厂
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        // 设置连接超时时间，单位为毫秒
        requestFactory.setConnectTimeout(5000);
        // 设置读取超时时间，单位为毫秒
        requestFactory.setReadTimeout(5000);

        // 创建 RestTemplate 实例并设置请求工厂
        RestTemplate restTemplate = new RestTemplate(requestFactory);

        // 获取消息转换器列表
        List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
        // 遍历消息转换器列表
        for (HttpMessageConverter<?> converter : messageConverters) {
            // 若为 StringHttpMessageConverter，则设置字符集为 UTF-8
            if (converter instanceof StringHttpMessageConverter) {
                ((StringHttpMessageConverter) converter).setDefaultCharset(StandardCharsets.UTF_8);
            }
        }

        return restTemplate;
    }
}
